// 接口请求封装
// 从环境变量读取配置（Vite 仅会暴露以 VITE_ 开头的变量）
const { VITE_API_BASE, VITE_REQUEST_TIMEOUT, VITE_USE_MOCK } = import.meta.env || {}
const BASE_URL = VITE_API_BASE || 'https://api.shequhuigou.com'
const REQ_TIMEOUT = Number(VITE_REQUEST_TIMEOUT) || 10000

// 仅在 H5 端按需加载 Mock 定义
let __mockModulePromise = null
// #ifdef H5
if (VITE_USE_MOCK === 'true') {
  __mockModulePromise = import('@/mock/index.js')
}
// #endif

const randomDelay = (min = 200, max = 600) => {
  const t = Math.floor(Math.random() * (max - min + 1)) + min
  return new Promise((r) => setTimeout(r, t))
}

// 请求拦截器
const requestInterceptor = (config) => {
  // 添加token
  const token = uni.getStorageSync('token')
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}`
    }
  }
  
  // 添加时间戳防止缓存
  if (config.method === 'GET') {
    config.url += (config.url.includes('?') ? '&' : '?') + '_t=' + Date.now()
  }
  
  return config
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response
  
  if (statusCode === 200) {
    if (data.code === 0) {
      return data.data
    } else if (data.code === 401) {
      // token过期，跳转登录
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
      uni.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none'
      })
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
      return Promise.reject(new Error('登录已过期'))
    } else {
      uni.showToast({
        title: data.message || '请求失败',
        icon: 'none'
      })
      return Promise.reject(new Error(data.message || '请求失败'))
    }
  } else {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
    return Promise.reject(new Error('网络错误'))
  }
}

// 统一请求方法
const request = (options) => {
  const config = requestInterceptor(options)
  
  return new Promise(async (resolve, reject) => {
    // 统一起始日志，便于在 Console 中看到
    console.log('[request][start]', { url: config.url, method: (config.method || 'GET').toUpperCase(), baseUrl: BASE_URL, useMock: VITE_USE_MOCK })
    // 确保 H5 下 Mock 规则已加载完成
    // #ifdef H5
    if (VITE_USE_MOCK === 'true' && __mockModulePromise) {
      try {
        const mod = await __mockModulePromise
        console.log('[request][mock-ready]')
        // 优先走本地匹配，避免真实网络请求被 Vite 返回 HTML
        if (mod && typeof mod.mockFetch === 'function') {
          try {
            const localPayload = await mod.mockFetch(config.url, config.method || 'GET', config.data)
            if (localPayload != null) {
              console.log('[request][mock-hit]', { url: config.url, method: config.method || 'GET' })
              try {
                const result = responseInterceptor({ statusCode: 200, data: localPayload })
                return resolve(result)
              } catch (error) {
                console.log('[request][mock-parse-error]', error)
                return reject(error)
              }
            }
          } catch (err) {
            console.log('[request][mock-local-failed]', err)
            // 失败则回落到真实请求
          }
        }
      } catch (e) {
        console.log('[request][mock-load-failed]', e)
      }
    }
    // #endif
    // 走真实 XHR（若上面未命中本地 Mock）
    // 在 H5 + Mock 场景下，使用相对路径，方便 Mock.js 拦截同源请求
    let finalUrl = BASE_URL + config.url
    // #ifdef H5
    if (VITE_USE_MOCK === 'true') {
      finalUrl = config.url
    }
    // #endif
    console.log('[request][final-url]', finalUrl)
    uni.request({
      url: finalUrl,
      method: config.method || 'GET',
      data: config.data || {},
      header: {
        'Content-Type': 'application/json',
        ...config.header
      },
      timeout: REQ_TIMEOUT,
      success: (res) => {
        console.log('[request][real-success]', { url: finalUrl, method: config.method || 'GET', statusCode: res.statusCode, data: res.data })
        try {
          const result = responseInterceptor(res)
          resolve(result)
        } catch (error) {
          console.log('[request][real-parse-error]', error)
          reject(error)
        }
      },
      fail: (error) => {
        console.log('[request][real-fail]', { url: finalUrl, method: config.method || 'GET', error })
        uni.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
}

// 封装常用请求方法
export const http = {
  get: (url, params = {}) => {
    return request({
      url,
      method: 'GET',
      data: params
    })
  },
  
  post: (url, data = {}) => {
    return request({
      url,
      method: 'POST',
      data
    })
  },
  
  put: (url, data = {}) => {
    return request({
      url,
      method: 'PUT',
      data
    })
  },
  
  delete: (url, data = {}) => {
    return request({
      url,
      method: 'DELETE',
      data
    })
  }
}

export default http